package cn.initcap.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 如何用一个5升杯子和一个3升杯子获取4升水
 *
 * @author initcap
 * @date Created in 2020/1/30 21:11.
 */
public class WaterPuzzle {

    private static final int FIRST_PUZZLE = 5;
    private static final int SEC_PUZZLE = 3;
    private static final int LAST_WATER = 4;
    private int[] pre;
    private int end;

    private WaterPuzzle() {
        Queue<Integer> queue = new LinkedList<>();
        boolean[] visited = new boolean[100];
        pre = new int[100];
        end = -1;

        queue.add(0);
        visited[0] = true;
        while (!queue.isEmpty()) {
            int cur = queue.remove();
            // a max FIRST_PUZZLE b max SEC_PUZZLE
            int a = cur / 10;
            int b = cur % 10;

            // 存储所有下一步的可能
            List<Integer> nexts = new ArrayList<>();
            // 装满
            nexts.add(FIRST_PUZZLE * 10 + b);
            nexts.add(a * 10 + SEC_PUZZLE);
            // 倒空
            nexts.add(0 * 10 + b);
            nexts.add(a * 10 + 0);
            // 互相倒水
            int x = Math.min(a, SEC_PUZZLE - b);
            int y = Math.min(FIRST_PUZZLE - a, b);
            nexts.add((a - x) * 10 + (b + x));
            nexts.add((a + y) * 10 + (b - y));

            for (int next : nexts) {
                if (!visited[next]) {
                    queue.add(next);
                    visited[next] = true;
                    pre[next] = cur;

                    if (next / 10 == LAST_WATER || next % 10 == LAST_WATER) {
                        end = next;
                        return;
                    }
                }
            }
        }

    }

    public static void main(String[] args) {
        System.out.println(new WaterPuzzle().result());
    }

    public Iterable<Integer> result() {
        List<Integer> res = new ArrayList<>();
        if (end == -1) {
            return res;
        }

        int cur = end;
        while (cur != 0) {
            res.add(cur);
            cur = pre[cur];
        }
        res.add(0);
        Collections.reverse(res);
        return res;
    }

}
